//
//  ZH_Window.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/10.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class BaseWindowController: NSWindowController {
    
    let titlebarHeight:CGFloat = 52
    
    private var _buttonsConstraints: [NSLayoutConstraint] = []
    private var _buttonGroupLeadingConstraint: NSLayoutConstraint?
    
    private var _regularConstraints: [NSLayoutConstraint] = []
    private var _fullScreenConstraints: [NSLayoutConstraint] = []
    

    var contentRect:CGRect = CGRect.zero
    var style:WindowStyle = .none
    
    
    override init(window: NSWindow?) {
        super.init(window: window)
    }
    
    lazy var contentWindow: NSWindow = {
        let contentWindow = NSWindow(contentRect: CGRect.zero, style: .none)
        return contentWindow
    }()
    
    //自定义------
    convenience init(contentRect:CGRect,style:WindowStyle,viewController:NSViewController) {
        
        let contentWindow = NSWindow(contentRect: contentRect, style: style)
        self.init(window: contentWindow)
        
        let frameSize = contentWindow.contentRect(forFrameRect: contentWindow.frame).size
        viewController.view.setFrameSize(frameSize)
        contentWindow.contentViewController = viewController
        
        self.window = contentWindow
        //self.contentWindow = contentWindow
        
        _updateTitlebarConstraints(with:Notification.init(name: NSWindow.willEnterFullScreenNotification))
        _updateTitlebarConstraints(with:Notification.init(name: NSWindow.didEnterFullScreenNotification))
        _updateTitlebarConstraints(with:Notification.init(name: NSWindow.willExitFullScreenNotification))
        _updateTitlebarConstraints(with:Notification.init(name: NSWindow.didExitFullScreenNotification))
        
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func _updateTitlebarConstraints(with notification: Notification) {
      guard
        let window = window,
        let titlebar = window.standardWindowButton(.closeButton)?.superview?.superview,
        let titlebarContainer = titlebar.superview
      else { return }
      
      titlebar.translatesAutoresizingMaskIntoConstraints = false
      
      switch notification.name {
        case NSWindow.willEnterFullScreenNotification:
          NSLayoutConstraint.deactivate(_regularConstraints)
          
        case NSWindow.didEnterFullScreenNotification:
          if _fullScreenConstraints.isEmpty {
            _fullScreenConstraints = [
              titlebar.leadingAnchor.constraint(equalTo: titlebarContainer.leadingAnchor),
              titlebar.trailingAnchor.constraint(equalTo: titlebarContainer.trailingAnchor),
              titlebar.topAnchor.constraint(equalTo: titlebarContainer.topAnchor),
              titlebar.heightAnchor.constraint(equalToConstant: 22)
            ]
          }
              
          NSLayoutConstraint.activate(_fullScreenConstraints)
          
        case NSWindow.willExitFullScreenNotification:
          NSLayoutConstraint.deactivate(_fullScreenConstraints)
          
        case NSWindow.didExitFullScreenNotification:
          fallthrough
          
        default:
          if _regularConstraints.isEmpty {
            _regularConstraints = [
              titlebar.leadingAnchor.constraint(equalTo: titlebarContainer.leadingAnchor),
              titlebar.trailingAnchor.constraint(equalTo: titlebarContainer.trailingAnchor),
              titlebar.topAnchor.constraint(equalTo: titlebarContainer.topAnchor),
              titlebar.heightAnchor.constraint(equalToConstant: 52)//.with(priority: .defaultLow)
            ]
          }
              
          NSLayoutConstraint.activate(_regularConstraints)
      }
    }
    
    func windowWillEnterFullScreen(_ notification: Notification) {
        _updateTitlebarConstraints(with: notification)
        //_updateButtonGroupConstraints()
    }
        
    func windowDidEnterFullScreen(_ notification: Notification) {
        _updateTitlebarConstraints(with: notification)
        //_updateButtonGroupConstraints()
    }
        
    func windowWillExitFullScreen(_ notification: Notification) {
        _updateTitlebarConstraints(with: notification)
        //_updateButtonGroupConstraints()
    }
        
    func windowDidExitFullScreen(_ notification: Notification) {
        _updateTitlebarConstraints(with: notification)
        //_updateButtonGroupConstraints()
    }

    func windowDidResize(_ notification: Notification) {
        _updateTitlebarConstraints(with: notification)
        //_updateButtonGroupConstraints()
    }
    
    
    private func _updateButtonGroupConstraints() {
      guard
        let window = window,
        let titlebar = window.standardWindowButton(.closeButton)?.superview,
        let titlebarContainer = titlebar.superview,
        let closeButton = window.standardWindowButton(.closeButton),
        let miniaturizeButton = window.standardWindowButton(.miniaturizeButton),
        let zoomButton = window.standardWindowButton(.zoomButton)
      else { return }
            
      // calculate leading spacing for button group
      let barHeight = window.styleMask.contains(.fullScreen) ? 22 : titlebarHeight
      let verticalSpacing = (barHeight - closeButton.frame.height) / 2
      let leadingOffset = max(7, min(verticalSpacing + 4, 12))
      
      let buttons = [closeButton, miniaturizeButton, zoomButton]
      
      // create constraints if needed
      if _buttonsConstraints.isEmpty {
        buttons.forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
        
        _buttonGroupLeadingConstraint = closeButton.leadingAnchor.constraint(equalTo: titlebar.leadingAnchor, constant: leadingOffset)
        
        _buttonsConstraints = [
          closeButton.centerYAnchor.constraint(equalTo: titlebar.centerYAnchor),
          miniaturizeButton.centerYAnchor.constraint(equalTo: titlebar.centerYAnchor),
          zoomButton.centerYAnchor.constraint(equalTo: titlebar.centerYAnchor),
          _buttonGroupLeadingConstraint!,
          miniaturizeButton.leadingAnchor.constraint(equalTo: closeButton.trailingAnchor, constant: 6),
          zoomButton.leadingAnchor.constraint(equalTo: miniaturizeButton.trailingAnchor, constant: 6)
        ]
        
        // activate constraints
        NSLayoutConstraint.activate(_buttonsConstraints)
        
        _updateButtonGroupTrackingArea(buttons: buttons)
      }
      
      // update leading constant
      _buttonGroupLeadingConstraint?.constant = leadingOffset
      titlebarContainer.layoutSubtreeIfNeeded()
    }
    
    
    private func _updateButtonGroupTrackingArea(buttons: [NSView]) {
      let themeView = buttons.first?.superview?.superview?.superview
      
      if let trackingArea = themeView?.trackingAreas.first(where: { $0.options.contains(.activeAlways) }) {
        // create a new tracking area with latest tracking rect
        let trackingRect = buttons.reduce(NSZeroRect, { $0.union($1.frame) })
        let newTrackingArea = NSTrackingArea(rect: trackingRect, options: trackingArea.options, owner: trackingArea.owner, userInfo: trackingArea.userInfo)
        // replace the tracking area
        themeView?.removeTrackingArea(trackingArea)
        themeView?.addTrackingArea(newTrackingArea)
      }
    }
}
